const express = require('express');
const router = express.Router();
const crypto = require('crypto');
const { db } = require('../app');

// API密钥验证中间件
function verifyApiKey(req, res, next) {
    const apiKey = req.headers['x-api-key'];
    
    if (!apiKey) {
        return res.status(401).json({ error: '缺少API密钥' });
    }

    db.get('SELECT * FROM api_keys WHERE key = ? AND is_active = 1', [apiKey], (err, key) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        if (!key) {
            return res.status(401).json({ error: '无效的API密钥' });
        }

        // 检查是否过期
        if (key.expires_at && new Date(key.expires_at) < new Date()) {
            return res.status(401).json({ error: 'API密钥已过期' });
        }

        req.apiKey = key;
        next();
    });
}

// 生成API密钥
router.post('/generate-key', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const { description, expires_in_days } = req.body;
    
    // 生成随机API密钥
    const apiKey = 'mc_' + crypto.randomBytes(32).toString('hex');
    
    // 计算过期时间
    let expiresAt = null;
    if (expires_in_days) {
        const expiresDate = new Date();
        expiresDate.setDate(expiresDate.getDate() + parseInt(expires_in_days));
        expiresAt = expiresDate.toISOString();
    }

    // 插入数据库
    db.run(
        'INSERT INTO api_keys (key, user_id, description, expires_at) VALUES (?, ?, ?, ?)',
        [apiKey, req.session.user.id, description || 'API密钥', expiresAt],
        function(err) {
            if (err) {
                return res.status(500).json({ error: '生成API密钥失败' });
            }
            
            res.json({
                success: true,
                api_key: apiKey,
                description: description || 'API密钥',
                expires_at: expiresAt,
                created_at: new Date().toISOString()
            });
        }
    );
});

// 获取API密钥列表
router.get('/keys', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    db.all(
        'SELECT ak.*, u.username as owner_name FROM api_keys ak LEFT JOIN users u ON ak.user_id = u.id ORDER BY ak.created_at DESC',
        (err, keys) => {
            if (err) {
                return res.status(500).json({ error: '获取API密钥列表失败' });
            }
            
            // 隐藏完整的API密钥
            const maskedKeys = keys.map(key => ({
                ...key,
                key: key.key.substring(0, 8) + '...' + key.key.substring(key.key.length - 8)
            }));
            
            res.json({ success: true, keys: maskedKeys });
        }
    );
});

// 删除API密钥
router.delete('/keys/:id', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const keyId = req.params.id;

    db.run('DELETE FROM api_keys WHERE id = ?', [keyId], (err) => {
        if (err) {
            return res.status(500).json({ error: '删除API密钥失败' });
        }
        res.json({ success: true, message: 'API密钥删除成功' });
    });
});

// 启用/禁用API密钥
router.put('/keys/:id/toggle', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const keyId = req.params.id;

    db.get('SELECT is_active FROM api_keys WHERE id = ?', [keyId], (err, key) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        if (!key) {
            return res.status(404).json({ error: 'API密钥不存在' });
        }

        const newStatus = key.is_active ? 0 : 1;
        
        db.run('UPDATE api_keys SET is_active = ? WHERE id = ?', [newStatus, keyId], (err) => {
            if (err) {
                return res.status(500).json({ error: '更新API密钥状态失败' });
            }
            
            res.json({
                success: true,
                message: `API密钥已${newStatus ? '启用' : '禁用'}`,
                is_active: newStatus
            });
        });
    });
});

// 获取服务器列表（API）
router.get('/servers', verifyApiKey, (req, res) => {
    const userId = req.apiKey.user_id;
    
    db.get('SELECT role FROM users WHERE id = ?', [userId], (err, user) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        
        let query;
        let params;
        
        if (user && user.role === 'admin') {
            query = 'SELECT * FROM servers ORDER BY created_at DESC';
            params = [];
        } else {
            query = 'SELECT * FROM servers WHERE user_id = ? ORDER BY created_at DESC';
            params = [userId];
        }
        
        db.all(query, params, (err, servers) => {
            if (err) {
                return res.status(500).json({ error: '获取服务器列表失败' });
            }
            
            res.json({
                success: true,
                servers: servers.map(server => ({
                    id: server.id,
                    name: server.name,
                    status: server.status,
                    port: server.port,
                    created_at: server.created_at
                }))
            });
        });
    });
});

// 获取服务器详情（API）
router.get('/servers/:id', verifyApiKey, (req, res) => {
    const serverId = req.params.id;
    const userId = req.apiKey.user_id;
    
    db.get('SELECT role FROM users WHERE id = ?', [userId], (err, user) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        
        let query;
        let params;
        
        if (user && user.role === 'admin') {
            query = 'SELECT * FROM servers WHERE id = ?';
            params = [serverId];
        } else {
            query = 'SELECT * FROM servers WHERE id = ? AND user_id = ?';
            params = [serverId, userId];
        }
        
        db.get(query, params, (err, server) => {
            if (err) {
                return res.status(500).json({ error: '获取服务器详情失败' });
            }
            if (!server) {
                return res.status(404).json({ error: '服务器不存在' });
            }
            
            res.json({
                success: true,
                server: {
                    id: server.id,
                    name: server.name,
                    status: server.status,
                    port: server.port,
                    config: JSON.parse(server.config || '{}'),
                    created_at: server.created_at
                }
            });
        });
    });
});

// 启动服务器（API）
router.post('/servers/:id/start', verifyApiKey, (req, res) => {
    const serverId = req.params.id;
    const userId = req.apiKey.user_id;
    
    db.get('SELECT role FROM users WHERE id = ?', [userId], (err, user) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        
        let query;
        let params;
        
        if (user && user.role === 'admin') {
            query = 'SELECT * FROM servers WHERE id = ?';
            params = [serverId];
        } else {
            query = 'SELECT * FROM servers WHERE id = ? AND user_id = ?';
            params = [serverId, userId];
        }
        
        db.get(query, params, (err, server) => {
            if (err) {
                return res.status(500).json({ error: '数据库错误' });
            }
            if (!server) {
                return res.status(404).json({ error: '服务器不存在' });
            }
            
            const { exec } = require('child_process');
            
            exec(`docker start ${server.docker_container_id}`, (error, stdout, stderr) => {
                if (error) {
                    return res.status(500).json({ error: '启动服务器失败' });
                }
                
                db.run('UPDATE servers SET status = ? WHERE id = ?', ['running', serverId]);
                res.json({ success: true, message: '服务器启动成功' });
            });
        });
    });
});

// 停止服务器（API）
router.post('/servers/:id/stop', verifyApiKey, (req, res) => {
    const serverId = req.params.id;
    const userId = req.apiKey.user_id;
    
    db.get('SELECT role FROM users WHERE id = ?', [userId], (err, user) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        
        let query;
        let params;
        
        if (user && user.role === 'admin') {
            query = 'SELECT * FROM servers WHERE id = ?';
            params = [serverId];
        } else {
            query = 'SELECT * FROM servers WHERE id = ? AND user_id = ?';
            params = [serverId, userId];
        }
        
        db.get(query, params, (err, server) => {
            if (err) {
                return res.status(500).json({ error: '数据库错误' });
            }
            if (!server) {
                return res.status(404).json({ error: '服务器不存在' });
            }
            
            const { exec } = require('child_process');
            
            exec(`docker stop ${server.docker_container_id}`, (error, stdout, stderr) => {
                if (error) {
                    return res.status(500).json({ error: '停止服务器失败' });
                }
                
                db.run('UPDATE servers SET status = ? WHERE id = ?', ['stopped', serverId]);
                res.json({ success: true, message: '服务器停止成功' });
            });
        });
    });
});

// 执行服务器命令（API）
router.post('/servers/:id/command', verifyApiKey, (req, res) => {
    const serverId = req.params.id;
    const userId = req.apiKey.user_id;
    const { command } = req.body;
    
    if (!command) {
        return res.status(400).json({ error: '命令不能为空' });
    }
    
    db.get('SELECT role FROM users WHERE id = ?', [userId], (err, user) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        
        let query;
        let params;
        
        if (user && user.role === 'admin') {
            query = 'SELECT * FROM servers WHERE id = ?';
            params = [serverId];
        } else {
            query = 'SELECT * FROM servers WHERE id = ? AND user_id = ?';
            params = [serverId, userId];
        }
        
        db.get(query, params, (err, server) => {
            if (err) {
                return res.status(500).json({ error: '数据库错误' });
            }
            if (!server) {
                return res.status(404).json({ error: '服务器不存在' });
            }
            
            const { exec } = require('child_process');
            
            exec(`docker exec ${server.docker_container_id} rcon-cli ${command}`, (error, stdout, stderr) => {
                if (error) {
                    return res.status(500).json({ error: '执行命令失败' });
                }
                
                res.json({
                    success: true,
                    message: '命令执行成功',
                    output: stdout
                });
            });
        });
    });
});

// 获取服务器日志（API）
router.get('/servers/:id/logs', verifyApiKey, (req, res) => {
    const serverId = req.params.id;
    const userId = req.apiKey.user_id;
    const lines = parseInt(req.query.lines) || 100;
    
    db.get('SELECT role FROM users WHERE id = ?', [userId], (err, user) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        
        let query;
        let params;
        
        if (user && user.role === 'admin') {
            query = 'SELECT * FROM servers WHERE id = ?';
            params = [serverId];
        } else {
            query = 'SELECT * FROM servers WHERE id = ? AND user_id = ?';
            params = [serverId, userId];
        }
        
        db.get(query, params, (err, server) => {
            if (err) {
                return res.status(500).json({ error: '数据库错误' });
            }
            if (!server) {
                return res.status(404).json({ error: '服务器不存在' });
            }
            
            const { exec } = require('child_process');
            
            exec(`docker logs --tail ${lines} ${server.docker_container_id}`, (error, stdout, stderr) => {
                if (error) {
                    return res.status(500).json({ error: '获取日志失败' });
                }
                
                res.json({
                    success: true,
                    logs: stdout.split('\n').filter(line => line.trim())
                });
            });
        });
    });
});

// 获取节点列表（API，仅管理员）
router.get('/nodes', verifyApiKey, (req, res) => {
    const userId = req.apiKey.user_id;
    
    db.get('SELECT role FROM users WHERE id = ?', [userId], (err, user) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        if (!user || user.role !== 'admin') {
            return res.status(403).json({ error: '没有权限' });
        }
        
        db.all('SELECT * FROM nodes ORDER BY created_at DESC', (err, nodes) => {
            if (err) {
                return res.status(500).json({ error: '获取节点列表失败' });
            }
            
            res.json({
                success: true,
                nodes: nodes.map(node => ({
                    id: node.id,
                    name: node.name,
                    host: node.host,
                    status: node.status,
                    created_at: node.created_at
                }))
            });
        });
    });
});

// 获取系统统计（API，仅管理员）
router.get('/stats', verifyApiKey, (req, res) => {
    const userId = req.apiKey.user_id;
    
    db.get('SELECT role FROM users WHERE id = ?', [userId], (err, user) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        if (!user || user.role !== 'admin') {
            return res.status(403).json({ error: '没有权限' });
        }
        
        // 获取各种统计信息
        const stats = {};
        
        // 用户统计
        db.get('SELECT COUNT(*) as total FROM users', (err, row) => {
            stats.total_users = row.total;
            
            db.get("SELECT COUNT(*) as active FROM users WHERE role = 'admin'", (err, row) => {
                stats.admin_users = row.total;
                
                // 服务器统计
                db.get('SELECT COUNT(*) as total FROM servers', (err, row) => {
                    stats.total_servers = row.total;
                    
                    db.get("SELECT COUNT(*) as running FROM servers WHERE status = 'running'", (err, row) => {
                        stats.running_servers = row.total;
                        
                        // 节点统计
                        db.get('SELECT COUNT(*) as total FROM nodes', (err, row) => {
                            stats.total_nodes = row.total;
                            
                            db.get("SELECT COUNT(*) as online FROM nodes WHERE status = 'online'", (err, row) => {
                                stats.online_nodes = row.total;
                                
                                res.json({
                                    success: true,
                                    stats: stats,
                                    timestamp: new Date().toISOString()
                                });
                            });
                        });
                    });
                });
            });
        });
    });
});

// 节点安装脚本下载
router.get('/node/install/:nodeId', (req, res) => {
    const nodeId = req.params.nodeId;
    
    db.get('SELECT * FROM nodes WHERE id = ?', [nodeId], (err, node) => {
        if (err) {
            return res.status(500).send('数据库错误');
        }
        if (!node) {
            return res.status(404).send('节点不存在');
        }
        
        // 获取面板公网IP
        db.get("SELECT value FROM settings WHERE key = 'panel_ip'", (err, setting) => {
            const panelIp = setting ? setting.value : 'localhost';
            
            const installScript = `#!/bin/bash
# Minecraft面板节点安装脚本
# 节点名称: ${node.name}
# 面板地址: ${panelIp}

echo "开始安装Minecraft面板节点..."

# 设置国内镜像源
echo "配置国内镜像源..."
sudo apt-get update
sudo apt-get install -y apt-transport-https ca-certificates curl software-properties-common

# 安装Docker（使用国内镜像）
curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun

# 配置Docker国内镜像
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://registry.docker-cn.com", "https://docker.mirrors.ustc.edu.cn"]
}
EOF

# 重启Docker服务
sudo systemctl daemon-reload
sudo systemctl restart docker

# 安装必要工具
sudo apt-get install -y sshpass wget unzip

# 创建Minecraft服务器目录
sudo mkdir -p /opt/minecraft-servers
sudo chown -R $USER:$USER /opt/minecraft-servers

echo "节点安装完成！"
echo "节点名称: ${node.name}"
echo "节点地址: ${node.host}"
echo "面板地址: ${panelIp}:3000"
`;
            
            res.setHeader('Content-Type', 'text/plain');
            res.setHeader('Content-Disposition', `attachment; filename="install-node-${nodeId}.sh"`);
            res.send(installScript);
        });
    });
});

module.exports = router;